var $name = $(".verifyInput:eq(0)");
var $phone = $(".verifyInput:eq(1)");
var $password = $(".verifyInput:eq(2)");
var $email = $(".verifyInput:eq(3)");
var $emailCode = $(".verifyInput:eq(4)");
var $nameDiv = $(".inputTypeCont:eq(0)");
var $emailDiv = $(".inputTypeCont:eq(3)");
var $emailCodeDiv = $(".inputTypeCont:eq(4)");

var $updateName = $(".verifyBtn:eq(0)");
var $deletePhone = $(".verifyBtn:eq(1)");
var $updatePhone = $(".verifyBtn:eq(2)");
var $updatePassword = $(".verifyBtn:eq(3)");
var $updateEmail = $(".verifyBtn:eq(4)");
var $sendEmail = $(".verifyBtn:eq(5)");

var $submit = $(".submitBtn");

var id = -1;
var name = '';
var phone = '未绑定';
var password = '';
var email = '';
var emailHasBeenSent = false;

var interval;

function updateEmail() {
    waitingForNextClick($updateEmail, 1, '重置');
    clearInterval(interval);
    $emailDiv.removeClass('noFrame');
    $updateEmail.val('重置');
    $updateEmail.attr('onclick', 'resetEmail()');
    $email.removeAttr('disabled');
    $email.focus();
    $email[0].selectedIndex = $name[0].length - 1;
    var j = parseFloat($emailCodeDiv.css('opacity'));
    interval = setInterval(function () {
        j = (j + 0.1);
        if (j > 1) {
            clearInterval(interval);
            $emailCodeDiv.removeAttr('disabled');
        }
        $emailCodeDiv.css('opacity', j);
    }, 10);
    checkSubmit();
}

function resetEmail() {
    waitingForNextClick($updateEmail, 1, '更改');
    clearInterval(interval);
    $emailDiv.addClass('noFrame');
    $updateEmail.val('更改');
    $updateEmail.attr('onclick', 'updateEmail()');
    $email.attr('disabled', 'disabled');
    $email.val(email);
    var i = parseFloat($emailCodeDiv.css('opacity'));
    interval = setInterval(function () {
        i = (i - 0.1);
        if (i < 0) {
            clearInterval(interval);
            $emailCodeDiv.attr('disabled', 'disabled');
        }
        $emailCodeDiv.css('opacity', i);
    }, 10);
    checkSubmit();
}

function updateName() {
    $nameDiv.removeClass('noFrame');
    $updateName.val('重置');
    $name.removeAttr('disabled');
    $name.focus();
    $name[0].selectedIndex = $name[0].length - 1;
    $updateName.attr('onclick', 'resetName()');
    checkSubmit();
}

function resetName() {
    $nameDiv.addClass('noFrame');
    $name.attr('disabled', 'disabled');
    $name.val(name);
    $updateName.val('更改');
    $updateName.attr('onclick', 'updateName()');
    checkSubmit();
}

function updatePhone() {
    layer.confirm('是否跳转页面去修改绑定的手机号码？\n本页面所做修改将自动保存。', function (index) {
        layer.close(index);
        if (checkSubmit()) {
            if (submit()) location.assign('/userCheckStart.html');
        } else location.assign('/userCheckStart.html');
    });
}

function deletePhone() {
    layer.confirm('确认解绑？', function (index) {
        $phone.val('未绑定');
        $updatePhone.removeAttr('onclick');
        $updatePhone.hide();
        $deletePhone.val('取消解绑');
        $deletePhone.attr('onclick', 'cancelDeletePhone()');
        checkSubmit();
        layer.close(index);
    }, function (index) {
        layer.close(index);
    });
}

function cancelDeletePhone() {
    $phone.val(phone);
    $deletePhone.attr('onclick', 'deletePhone()');
    $deletePhone.val('解绑');
    $updatePhone.show();
    $updatePhone.attr('onclick', 'updatePhone()');
    checkSubmit();
}

function sendEmail() {
    if (!test_ipt(testEmail, $email, $("label[for=email]"))) {
        layer.msg('邮箱地址不正确');
        $email.focus();
        return false;
    } else if ($email.val() === email) {
        layer.msg('请修改邮箱地址');
        $email.focus();
        return false;
    }
    var load = layer.load();
    $.getJSON("/email/sendEmail.do", {email: $email.val()}, function (data) {
        layer.close(load);
        layer.msg(data.message);
        if (data.status === 0) {
            waitingForNextClick($sendEmail, 60, '发送验证码');
            var interval001 = setInterval(function () {
                $.getJSON("/email/bindAutoVerify.do", {email: $email.val()}, function (data) {
                    if (data.status === 0) {
                        emailHasBeenSent = true;
                        $emailCode.val(data.message);
                        clearInterval(interval001);
                    } else if (data.status === 1) {
                        clearInterval(interval001);
                    } else if (data.status === -404) {
                        location.assign('/login.html');
                    }
                });
            }, 10000);
        }
    });
}

function updatePassword() {
    layer.prompt({title: '请输入原始密码', formType: 1}, function (pass, index) {
        var loadId = layer.msg('正在验证', {icon: 16, shade: 0.1, time: 0});
        $.post('/wx/checkPass.do', {password: pass}, function (data) {
            layer.close(loadId);
            if (data.status === 0) {
                layer.close(index);
                layer.open({
                    type: 1,
                    title: '修改密码',
                    closeBtn: 1,
                    btn: ['确定', '取消'],
                    shadeClose: true,
                    content: '<div style="margin: 20px 20px 0 20px"><table style="margin: 0 auto; padding: 0; border-collapse: collapse; border-spacing: 0"><tr><td style="background-color: #efefef; padding: 0 10px; width:90px; border: 1px solid #88a; text-align: right"><label for="new" style="color: #669">新密码</label></td><td style="font-size: 14px; width:190px; border: 1px solid #88a;"><input id="new" style="font-size: 14px; padding-left: 10px; border: none; outline: none; height: 30px" type="password" maxlength="32"></td></tr><tr><td style="background-color: #efefef; padding: 0 10px; width:90px; border: 1px solid #88a; text-align: right"><label for="confirm" style="color: #669">确认密码</label></td><td style="font-size: 14px; width:190px; border: 1px solid #88a;"><input id="confirm" style="font-size: 14px; padding-left: 10px; border: none; outline: none; height: 30px" type="password" maxlength="32"></td></tr></table></div>',
                    yes: function (index) {
                        var $new = $("#new");
                        if (!test_ipt(testPasswd, $new, $("label[for=new]"))) {
                            $new.focus();
                            layer.msg('密码格式不正确');
                            return;
                        }
                        if ($new.val() === pass) {
                            layer.msg('这个密码不就是原来的密码吗。。。');
                            return;
                        }
                        if ($new.val() !== $("#confirm").val()) {
                            layer.msg('两次密码不一致');
                        } else {
                            password = $new.val();
                            $password.val(password);
                            $updatePassword.attr('onclick', 'resetPassword()');
                            $updatePassword.val('重置');
                            checkSubmit();
                            layer.msg('密码修改完成，点击确认修改提交。<br>修改后记得用新密码登录哦~', {closeBtn: 1, time: 0});
                            layer.close(index);
                        }
                    }
                });
            } else {
                layer.msg(data.message);
            }
        });
    });
}

function resetPassword() {
    $password.val('');
    $updatePassword.val('更改');
    $updatePassword.attr('onclick', 'updatePassword()');
    password = '';
    checkSubmit();
}

function checkSubmit() {
    if ($updateName.val() === '重置' ||
        $deletePhone.val() === '取消解绑' ||
        $updatePassword.val() === '重置' ||
        $updateEmail.val() === '重置') {
        $submit.css('background', '#cc2020');
        $submit.attr('onclick', 'submit()');
        return true;
    } else {
        $submit.css('background', '#888');
        $submit.removeAttr('onclick');
        return false;
    }
}

function submit() {
    var data = {};

    if (!test_ipt(testName, $name, $("label[for=name]"))) {
        layer.msg('用户名不合法');
        $name.focus();
        return false;
    } else if (name !== $name.val()) {
        data.name = $name.val();
    }

    if ($phone.val() === '未绑定' && phone !== '未绑定') {
        data.phone = '未绑定';
    }

    if ($password.val() !== '' && password !== '') {
        data.password = password;
    }

    if (!test_ipt(testEmail, $email, $("label[for=email]"))) {
        layer.msg('邮箱地址不正确');
        $email.focus();
        return false;
    } else if (email !== $email.val()) {
        if (!test_ipt(/\d{6}/, $emailCode, $("label[for=verify]"))) {
            layer.msg('验证码不正确');
            $emailCode.focus();
            return false;
        } else if (emailHasBeenSent) {
            data.email = $email.val();
            data.code = $emailCode.val();
        } else {
            layer.msg('请先发送验证码验证邮箱');
            return false;
        }
    }

    if (Object.keys(data).length === 0 && $phone.val() === phone) {
        layer.msg('还没有做任何修改呢');
        return true;
    }
    data.id = id;
    var load = layer.load();
    var flag = false;
    $.ajax({
        url: '/wx/updateUserInfo.do',
        data: data,
        type: 'POST',
        async: false,
        dataType: 'JSON',
        success: function (data) {
            layer.close(load);
            layer.msg(data.message);
            if (data.status > 0) {
                flag = true;
                if (name !== $name.val()) {
                    name = $name.val();
                }
                if ($phone.val() !== phone) {
                    phone = $phone.val();
                    if (phone === '未绑定') {
                        $deletePhone.hide();
                    }
                }
                if (email !== $email.val()) {
                    email = $email.val();
                }
                resetName();
                cancelDeletePhone();
                resetEmail();
                resetPassword();
                $emailCode.val('');
            }
        },
        error: function () {
            layer.close(load);
            layer.msg('提交修改失败<br>网络的原因？');
        }
    });
    return flag;
}

$(function () {
    $emailCodeDiv.css('opacity', 0);
    $emailCodeDiv.attr('disabled', 'disabled');
    $phone.css('width', '120px');

    // 初始化用户信息
    function init() {
        setTimeout(function () {
            if (user === undefined) {
                init();
                return;
            }
            $name.val(user.name);
            if (user.phone === undefined || user.phone === '未绑定' || user.phone === '') {
                $phone.val('未绑定');
                phone = '未绑定';
                $deletePhone.removeAttr('onclick');
                $deletePhone.hide();
            } else {
                $phone.val(user.phone);
                phone = user.phone;
            }
            $password.val('');
            $email.val(user.email);
            id = user.id;
            name = user.name;
            email = user.email;
        }, 200);
    }
    init();

    $updateName.attr('onclick', 'updateName()');
    $updatePhone.attr('onclick', 'updatePhone()');
    $deletePhone.attr('onclick', 'deletePhone()');
    $updatePassword.attr('onclick', 'updatePassword()');
    $updateEmail.attr('onclick', 'updateEmail()');
    $sendEmail.attr('onclick', 'sendEmail()');
});